﻿using System;
using ch10.binary;
using ch10.binary.type;
using ch10.instance;

namespace ch10.interpreter
{
    using WasmVal = Object;

    public struct GlobalVar : IGlobal
    {
        private readonly GlobalType _type;
        private ulong _val;

        public GlobalVar(GlobalType type, ulong val) 
        {
            _type = type;
            _val = val;
        }

        public GlobalType Type()
        {
            return _type;
        }

        public ulong GetAsU64()
        {
            return _val;
        }

        public void SetAsU64(ulong val)
        {
            if (_type.Mut != 1)
            {
                Panic.Run(Errors.ErrImmutableGlobal);
            }

            this._val = val;
        }

        public WasmVal Get()
        {
            return Instr.WrapU64(_type.ValType, _val);
        }

        public void Set(WasmVal val)
        {
            _val = Instr.UnwrapU64(_type.ValType, val);
        }
    }
}